package com.effectiv.req1.business.api;

import java.io.Serializable;



import javax.annotation.PostConstruct;

import jodd.bean.BeanUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.repository.MongoRepository;

import com.effectiv.req1.domain.Company;
import com.effectiv.req1.domain.User;
import com.effectiv.req1.security.SecurityUtil;
import com.google.common.eventbus.EventBus;
import com.mongodb.DBObject;

@Slf4j
public abstract class AbstractBusinessService<T, Id extends Serializable> extends AbstractMongoEventListener<T>
		implements BusinsessService<T, Id> {

	@Autowired
	private MongoTemplate template;
	@Autowired
	private EventBus bus;

	@Getter
	@Setter
	private MongoRepository repository;

	private final String CREATED_BY = "createdBy";
	private final String LAST_UPDATED_BY = "lastUpdatedBy";
	
	
	public void post(Object event) {
		log.info("Event posted = {}", event);
		
		if(event != null){
			bus.post(event);
		}
	}
	
	
	@Override
	public T update(T t) {
		// populate ---- special fields
		//fetch pre-image and save asynchronously.
		
		User user = getUser();
		
		if (user != null) {
			BeanUtil.setPropertySilent(t, LAST_UPDATED_BY, user);	
		}
		
		return (T) repository.save(t);
		

	}
	
	

	@Override
	public void save(T t) {

		// populate ---- special fields

		User user = getUser();
		
		if (user != null) {
			BeanUtil.setPropertySilent(t, CREATED_BY, user);
			BeanUtil.setPropertySilent(t, LAST_UPDATED_BY, user);
			
		}
		
		repository.save(t);
	}
	
	

	@Override
	public T findOne(Id id) {
		return (T) repository.findOne(id);
	}

	@Override
	public Company getCompany() {
		return SecurityUtil.getUserDetails().getCompany();
	}

	@Override
	public User getUser() {
		return SecurityUtil.getUserDetails();
	}
	
	public boolean isCompanyAdmin(){
		return SecurityUtil.isCompanyAdmin();
	}

	@PostConstruct
	private void init() {
		if(!template.collectionExists("t_project_activity")) {
			CollectionOptions options = new CollectionOptions(1024, 50, true);
			template.createCollection("t_project_activity", options);
		}
		
		initInternal();
	}

	protected abstract void initInternal();

	

	@Override
	public void delete(T t) {
		//fetch pre-image and save asynchronously.
		repository.delete(t);
		
	}



	

}
